/**
 * Created by jiadx on 2016/3/18.
 */
'use strict';

angular.module('Query')
    .controller('SingleProductStreamController', ['$scope', '$http', '$q', '$stateParams', 'PublicModule', 'PublicEnum', 'usbPort', 'PublicFunction',
        function($scope, $http, $q, $stateParams, PublicModule, PublicEnum, usbPort, PublicFunction) {
            PublicModule.initModule($scope, 'BarcodeMaster');

            $scope.data = {
                bizCatalog: [],
                bizRecords: {
                    record: []
                },
                Barcode: '',
                productParam: {},
                icon_position: {}
            };

            $scope.unfold = function(index) {
                var h = 0;
                for (var i = 0; i < index; i++) {
                    h += (angular.element('.list-exp_' + i).outerHeight() - 34);
                }
                angular.element('.query-context').scrollTop(h);
            };

            $scope.$on('usbPort.input', function(e, inputStr) {
                if ($scope.Module.BarcodeMaster.FocusedRecord === null) {
                    $scope.Module.BarcodeMaster.FocusedRecord = {};
                }
                $scope.Module.BarcodeMaster.FocusedRecord.BarcodeMaster = {
                    Barcode: inputStr
                };
                $scope.$apply();
                $scope.search();
            });

            $scope.$on('$destroy', function() {
                usbPort.stop();
            });

            function queryProduct(Barcode) {
                var defer = $q.defer();
                $http({
                    method: 'POST',
                    url: 'api/ProductFlow/getProductFlow',
                    data: {
                        Parameter: {
                            Barcode: Barcode
                        }
                    }
                }).success(function(result) {
                    defer.resolve(result);
                }).error(function(error) {
                    defer.reject(error);
                });

                return defer.promise;
            }

            $scope.search = function(remoteBarcode) {
                var BarcodeMaster;
                if ($scope.Module.BarcodeMaster && $scope.Module.BarcodeMaster.FocusedRecord !== null) {
                    BarcodeMaster = $scope.Module.BarcodeMaster.FocusedRecord.BarcodeMaster;
                } else {
                    BarcodeMaster = undefined;
                }
                var barcode = BarcodeMaster ? BarcodeMaster.Barcode : remoteBarcode;
                if (barcode) {
                    queryProduct(barcode).then(function(strr) {
                            if (!strr) {
                                PublicFunction.tip("", "没有对应的流水信息");
                                return;
                            }
                            if (!strr.Data) {
                                PublicFunction.tip("", "没有对应的流水信息");
                                return;
                            }
                            angular.forEach(strr.Data.bizCatalog, function(value) {
                                value.record = strr.Data.bizRecords[value.UniqueId];
                                angular.forEach(value.record, function(rec) {
                                    var uString = '';
                                    angular.forEach(rec.Users, function(u) {
                                        uString = uString + u.Name + ' ';
                                    });
                                    rec.Users = [{ Name: uString }];
                                    rec.CollectDateTime = dateFormat(rec.CollectDateTime, "yyyy-MM-dd hh:mm:ss");
                                    var h = 0,
                                        m = 0,
                                        s = 0;
                                    if (rec.WorkTime) {
                                        h = Math.floor(rec.WorkTime / 3600);
                                        m = Math.floor((rec.WorkTime - h * 3600) / 60);
                                        s = rec.WorkTime - h * 3600 - m * 60;
                                        rec.WorkTime = h + ':' + m + ':' + Math.round(s);
                                    }
                                });
                            });
                            $scope.Module.BarcodeMaster.FocusedRecord = {};
                            $scope.Module.BarcodeMaster.FocusedRecord.BarcodeMaster = {
                                Barcode: barcode
                            };
                            if (strr.Data.basicInfo.StartDateTime) {
                                strr.Data.basicInfo.StartDateTime = dateFormat(strr.Data.basicInfo.StartDateTime, "yyyy-MM-dd hh:mm:ss");
                            }

                            if (strr.Data.basicInfo.RealStartDateTime) {
                                strr.Data.basicInfo.RealStartDateTime = dateFormat(strr.Data.basicInfo.RealStartDateTime, "yyyy-MM-dd hh:mm:ss");
                            }
                            if (strr.Data.basicInfo.EndDateTime) {
                                strr.Data.basicInfo.EndDateTime = dateFormat(strr.Data.basicInfo.EndDateTime, "yyyy-MM-dd hh:mm:ss");
                            }

                            if (strr.Data.basicInfo.RealEndDateTime) {
                                strr.Data.basicInfo.RealEndDateTime = dateFormat(strr.Data.basicInfo.RealEndDateTime, "yyyy-MM-dd hh:mm:ss");
                            }

                            $scope.data = {
                                basicInfo: strr.Data.basicInfo,
                                bizCatalog: strr.Data.bizCatalog,
                                bizRecords: strr.Data.bizRecords,
                                productParam: strr.Data.productParam
                            };
                        },
                        function() {

                        });
                }
            };

            $scope.init = function() {
                $scope.search($stateParams.Barcode);
                usbPort.start();
            };
            $scope.init();

            function dateFormat(dateStr, fmt) { //author: meizz 
                var date = new Date(dateStr);
                var o = {
                    "M+": date.getMonth() + 1, //月份   
                    "d+": date.getDate(), //日   
                    "h+": date.getHours(), //小时   
                    "m+": date.getMinutes(), //分   
                    "s+": date.getSeconds(), //秒   
                    "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
                    "S": date.getMilliseconds() //毫秒   
                };
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                }
                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(fmt)) {
                        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    }
                }
                return fmt;
            }


        }
    ])

.directive("myScroll", function($window) {
    return function(scope, element, attrs) {
        var scrollEl = angular.element('div[class=query-context]');
        scrollEl.scroll(onScroll);

        scope.$on('$destroy', function() {
            scrollEl.off('scroll', onScroll);
        });

        function onScroll() {
            for (var i = 0; i < scope.data.bizCatalog.length + 2; i++) {
                var show_top = angular.element('.list-exp_' + i).offset().top,
                    hide_top = 139 + i * 35;
                if (show_top <= hide_top) {
                    angular.element('.list-icon-fix_' + i).removeClass('list-icon-hide');
                    angular.element('.list-icon_' + i).addClass('list-icon-show list-icon-hide-cursor');

                    for (var j = 0; j < i; j++) {
                        angular.element('.list-icon_' + j).removeClass('list-icon-show');
                    }
                    angular.element('.exp_' + i).addClass('list-icon-hide');
                } else {
                    angular.element('.exp_' + i).removeClass('list-icon-hide');
                    angular.element('.list-icon_' + i).removeClass('list-icon-show list-icon-hide-cursor');
                    angular.element('.list-icon-fix_' + i).addClass('list-icon-hide');
                }
            }
        }

    };
});
